package com.thinkfit.jy.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.CalendarView;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.bean.SportInfoBean;
import com.common.lib.bean.SportRecordBean;
import com.common.lib.bean.UserBean;
import com.common.lib.bean.VideoBean;
import com.common.lib.constant.Constants;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.manager.DataManager;
import com.common.lib.utils.BaseUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.thinkfit.jy.R;
import com.thinkfit.jy.activity.VideoCourseInfoActivity;
import com.thinkfit.jy.adapter.CollectVideoAdapter;
import com.thinkfit.jy.adapter.SportRecordAdapter;
import com.thinkfit.jy.contract.SportRecordContract;
import com.thinkfit.jy.presenter.SportRecordPresenter;
import com.thinkfit.jy.utils.ToastUtils;

import java.util.ArrayList;

/**
 * 数据中心（原用户累计数据记录）
 */
public class SportRecordFragment extends BaseFragment<SportRecordContract.Presenter> implements SportRecordContract.View, OnRefreshLoadMoreListener {

    private UserProfileFragment mUserProfileFragment;

    ImageView ivUserHead,ivUserCut,ivVipLevel,ivSex;
    TextView tvUserName,tvUserDistance,tvUserTime,tvUserKcal,tvDaysExercise,tvSportNum,tvCollectType,tvLive,tvCourse;
    CalendarView calendarView;
    RecyclerView rvCollect;
    ScrollView svCollect;
    private int mPage;
    private int type = 1;

    boolean isShowCollect = true;
    CollectVideoAdapter collectVideoAdapter;
    @NonNull
    @Override
    protected SportRecordContract.Presenter onCreatePresenter() {
        return new SportRecordPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_data_hub;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        UserBean myInfo = DataManager.Companion.getInstance().getMyInfo();

        ivUserHead = view.findViewById(R.id.iv_user_head);
        ivUserCut = view.findViewById(R.id.iv_user_cut);
        tvUserName = view.findViewById(R.id.tv_user_name);
        ivVipLevel = view.findViewById(R.id.iv_vip_level);
        ivSex = view.findViewById(R.id.iv_sex);
        tvUserDistance = view.findViewById(R.id.tv_user_distance);
        tvUserTime = view.findViewById(R.id.tv_user_time);
        tvUserKcal = view.findViewById(R.id.tv_user_kcal);
        tvDaysExercise = view.findViewById(R.id.tv_days_exercise);
        tvSportNum = view.findViewById(R.id.tv_sport_num);
        calendarView = view.findViewById(R.id.calendarView);
        rvCollect = view.findViewById(R.id.rv_collect);
        svCollect = view.findViewById(R.id.sv_collect);
        tvCollectType = view.findViewById(R.id.tv_collect_type);
        tvLive = view.findViewById(R.id.tv_live);
        tvCourse = view.findViewById(R.id.tv_course);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        rvCollect.setLayoutManager(linearLayoutManager);
        rvCollect.setAdapter(getAdapter());

        if(myInfo != null){
            tvUserName.setText(myInfo.getNickname());
            if(myInfo.getSex() == 1){
                ivSex.setImageResource(R.drawable.img_home_sex_boy);
            }else {
                ivSex.setImageResource(R.drawable.img_home_sex_girl);
            }
            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
        }else {
//            tvUserName.setText(getString(R.string.app_main_user_name,getString(R.string.app_main_guest)));
            ivUserHead.setImageResource( R.drawable.app_not_login);
//            BaseUtils.StaticParams.loadImage(getContext(), R.drawable.app_not_login, myInfo.getHeadimg(),ivUserHead);
//            tvHint.setText(getString(R.string.app_main_login_please));
        }

        calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
                // 当用户选择了一个新的日期时，这个方法会被调用
                // year, month, dayOfMonth 分别代表年、月、日（注意：月份是从0开始的，即0代表1月）
                String date = dayOfMonth + "/" + (month + 1) + "/" + year; // 格式化日期显示
//                ToastUtils.getInstance().show( getContext(),"选中的日期是: " + date);
            }
        });

        tvCollectType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isShowCollect){
                    isShowCollect = false;
                    svCollect.setVisibility(View.VISIBLE);
                }else {
                    isShowCollect = true;
                    svCollect.setVisibility(View.GONE);
                }
            }
        });

        tvLive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = 4;
                mPage = 1;
                tvCollectType.setText(getString(R.string.app_live));
                getPresenter().getVideoCourse(type,mPage);
                svCollect.setVisibility(View.GONE);
            }
        });
        tvCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = 1;
                mPage = 1;
                tvCollectType.setText(getString(R.string.app_course));
                getPresenter().getVideoCourse(type,mPage);
                svCollect.setVisibility(View.GONE);
            }
        });
        if(myInfo != null){
            getPresenter().getSportInfo();
        }


    }

    public CollectVideoAdapter getAdapter(){
        if(collectVideoAdapter == null){
            collectVideoAdapter = new CollectVideoAdapter(getContext());
        }
        collectVideoAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                VideoBean bean = collectVideoAdapter.getItem(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constants.BUNDLE_EXTRA, bean);
                bundle.putSerializable(Constants.BUNDLE_EXTRA_2, bean.getType());
                openActivity(VideoCourseInfoActivity.class, bundle);
            }
        });
        return collectVideoAdapter;
    }

    @Override
    public void onResume() {
        super.onResume();
        mPage = 1;
        getPresenter().getVideoCourse(type,mPage);
    }

    public SportRecordFragment setParentFragment(UserProfileFragment fragment) {
        mUserProfileFragment = fragment;
        return this;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void getSportInfoSuccess(SportInfoBean bean) {
        if (getView() == null) {
            return;
        }
        tvUserDistance.setText(bean.getDistance());
        tvUserTime.setText((bean.getAlltime()/60)+"");
        tvUserKcal.setText(bean.getKcal());
        tvSportNum.setText(bean.getTimes()+"");

//        setText(R.id.tvTotalTime, String.valueOf(bean.getAlltime() / 60));
//        setText(R.id.tvDistance, bean.getDistance());
//        setText(R.id.tvKcal, bean.getKcal());
    }

    @Override
    public void getSportRecordSuccess(int page, ArrayList<SportRecordBean> list) {
        if (getView() == null) {
            return;
        }
        mPage = page;
//        if (page == 1) {
//            getAdapter().setNewInstance(list);
//        } else {
//            getAdapter().addData(list);
//        }
        finishLoad();
    }

    @Override
    public void getSportRecordFailed() {
        if (getView() == null) {
            return;
        }
        finishLoad();
    }

    @Override
    public void getVideoCourseFailed() {
        if (getView() == null) {
            return;
        }
        finishLoad();
    }

    @Override
    public void getVideoCourseSuccess(int page, ArrayList<VideoBean> list) {
        mPage = page;
        if (page == 1) {
            getAdapter().setNewInstance(list);
        } else {
            getAdapter().addData(list);
        }
        finishLoad();
    }

    private void finishLoad() {
        SmartRefreshLayout layout = getView().findViewById(R.id.smartRefreshLayout);
        layout.finishLoadMore();
        layout.finishRefresh();
        layout.setEnableLoadMore(getAdapter().getItemCount() != 0
                && getAdapter().getItemCount() % 9 == 0);

        if (getAdapter().getItemCount() == 0) {
            rvCollect.setVisibility(View.GONE);
            setViewVisible(R.id.tvNoCourse);
        } else {
            rvCollect.setVisibility(View.VISIBLE);
            setViewGone(R.id.tvNoCourse);
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        getPresenter().getVideoCourse(type,mPage + 1);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        getPresenter().getVideoCourse(type,1);
//        getPresenter().getSportInfo();
    }
}
